package com.raquel.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/** 
 * @author Raquel Valenzuela
 * Servlet implementation class SignIn
 * checks the entered login data
 */
@WebServlet("/SignIn")
public class SignIn extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignIn() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * redirects to login.jsp
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
	}

	/**
	 * validates inserted data
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		
		//PrintWriter output=response.getWriter();
		String login = request.getParameter("login");
		String password= request.getParameter("password");
		
		//validating values of login
		Pattern pattern = Pattern.compile("^[a-z0-9]{8}$");
		java.util.regex.Matcher loginChecker = pattern.matcher(login);
		Pattern patternPass = Pattern.compile("^[a-z0-9]{8}$");
		java.util.regex.Matcher loginCheckerPass = patternPass.matcher(password);
		
		boolean anyError= false;
		
		if(!loginChecker.find()){
			request.setAttribute("loginerror","Login Incorrect");
			System.out.println("Login incorrect");
			anyError=true;
		}
		
		if(!loginCheckerPass.find()){
			request.setAttribute("passerror","Password Incorrect");
			System.out.println("Password incorrect");
			anyError=true;
		}
		
		if(anyError){
			this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
			
		}else{
			session.setAttribute("login", login);
			this.getServletContext().getRequestDispatcher("/Private").forward(request, response);
			System.out.println("Login correct");
		}
	}
}


